package crack.ch1;

/**
 * @author Pavel Belevich
 *         Date: 6/30/12
 *         Time: 4:25 PM
 */
public class Problem4 {
    
    static char[] f(char[] chars) {
        for (int i = 0 ; i < chars.length; i++) {
            if (chars[i] == ' ') {
                for (int j = chars.length-1 ; j >= i+2 ; j--) {
                    chars[j] = chars[j-2];
                }
                chars[i] = '%';
                chars[i+1] = '2';
                chars[i+2] = '0';
            }
        }
        return chars;
    }

    static char[] replaceSpaces(char[] str, int length) {
        int spaceCount = 0;
        for (int i = 0 ; i < length ; i++) {
            if (' ' == str[i]) spaceCount++;
        }
        int newLength = length + spaceCount * 2;
        for (int i = length - 1; i >= 0 ; i--) {
            if (' ' == str[i]) {
                str[--newLength] = '0';
                str[--newLength] = '2';
                str[--newLength] = '%';
            } else {
                str[--newLength] = str[i];
            }
        }
        return str;
    }

    public static void main(String[] args) {
        char[] chars = f("Mr John Smith    ".toCharArray());
        System.out.println("chars = " + new String(chars));

        String s = "Mr John Smith    ";
        chars = replaceSpaces(s.toCharArray(),s.trim().length());
        System.out.println("chars = " + new String(chars));
    }
    
}
